import '../css/cart.scss';
import Header from '../components/header/index';
import { CartModel } from '../models/cart';
import CartListItem from '../components/cart/list_item/index';
import PurchaseBox from '../components/cart/purchase_box/index';
import NoListTip from '../components/cart/no_list_tip/index';
import Toast from '../components/toast';

const header = new Header(),
  cartModel = new CartModel(),
  cartListItem = new CartListItem(),
  purchaseBox = new PurchaseBox(),
  noListTip = new NoListTip(),
  toast = new Toast();

const App = (doc) => {
  const oContainer = doc.getElementsByClassName('J_container')[0],
    oList = doc.getElementsByClassName('J_list')[0];

  const cartInfos = {
    list: [],
    total: 0
  }

  const doms = {
    oTotal: null,
    oMainCheck: null,
    oEditRemove: null,
    oPurchaseBtn: null,
    oPurchaseBox: null,
    oSubChecks: null
  }

  const init = () => {
    oContainer.appendChild(header.tpl({
      title: '购物车管理',
      is_show: true,
      content: '编辑'
    }));

    cartModel.getCartList(1).then((res) => {
      cartInfos.list = res.res;
      cartInfos.total = res.total_price;

      oList.innerHTML = cartListItem.makeList(cartInfos.list);

      oContainer.appendChild(purchaseBox.tpl(cartInfos.total));
    }).then(() => {
      bindEvent();
    })
  }

  const bindEvent = () => {
    doms.oMainCheck = doc.getElementsByClassName('J_mainCheck')[0]; //找的是动态插入的组件，要在插入后， then后面
    doms.oEditRemove = doc.getElementsByClassName('J_editRemove')[0];
    doms.oPurchaseBtn = doc.getElementsByClassName('J_purchase')[0];
    doms.oTotal = doc.getElementsByClassName('J_totalPrice')[0];
    doms.oPurchaseBox = doc.getElementsByClassName('purchase-box')[0];
    doms.oSubChecks = doc.getElementsByClassName('J_subCheck');

    oList.addEventListener('click', listEvent, false);
    doms.oMainCheck.addEventListener('click', selectAll, false);
    doms.oEditRemove.addEventListener('click', header.onShowRemoveBtn, false);
    doms.oPurchaseBtn.addEventListener('click', purchaseCart, false);
  }

  const listEvent = (e) => {

    cartListItem.listEvent(e).then(res => {

      

      if (res !== -1) {
        //set index
        res.idx = returnIndex(res.id, cartInfos);

        let infoItem = cartInfos.list[res.idx]; //dataInfo item
        console.log(res.id)

        switch (res.field) {
          case 'numSelector':
            numOperation(infoItem, res, doms.oTotal);
            break;
          case 'checkBox':
            itemCheck(infoItem, res, doms.oTotal);
            break;
          case 'remove':
            removeItem(res, doms.oTotal);
          default:
            break;
        }
      } else {
        console.log('ignore');
      }
    })
  }

  const returnIndex = (id, cartInfos) =>{
    let index;
    cartInfos.list.forEach((elem, idx) => {
      if(id === elem.id){
        index = idx;
      }
    });
    return index;
  }

  
  const numOperation = (infoItem, res, dom) => {
    infoItem.num = res.num;
    
    infoItem.total_price = infoItem.price * infoItem.num;
    doms.oSubChecks[res.idx].checked = true;
    cartInfos.list[res.idx].checked = true;  
    //select subCheck
    reComputePrice(dom);
  }

  const itemCheck = (infoItem, res, dom) => {
    infoItem.checked = res.checked;
    reComputePrice(dom);
  }

  const removeItem = (res, dom) => {

    cartInfos.list.splice(res.idx, 1);

    if (cartInfos.list.length > 0) {
      reComputePrice(dom);
    } else {

      doms.oPurchaseBox.remove();
      oList.innerHTML = noListTip.tpl();
    }

  }

  const selectAll = (e) => {
    purchaseBox.selectAll(e, cartInfos);
    reComputePrice(doms.oTotal);
  }

  const purchaseCart = () => {
    let goodsIds = []; //goods ID array, it will send as a String by toString() function

    //push goods id
    cartInfos.list.forEach((elem) => {
      if (elem.checked) {
        goodsIds.push(elem.id);
      }
    });

    //check goosIds 
    if (goodsIds.toString() === '') {
      toast.showToast({
        icon: 'warning',
        title: '请选择商品',
        duration: 1500
      });
      return;
    }

    //use model to send
    cartModel.purchaseCart(1, goodsIds.toString()).then(res => {
      let code = res.msg_code,
          dataArr = [];
      if (code === '200') {
        toast.showToast({
          icon: 'success',
          title: '购买成功'
        });

        //delete bought goods info and push it in a new array
        cartInfos.list.forEach((elem, index) => {
          if (elem.checked === false) {
            dataArr.push(elem);
          }
        });

        //change cartInfos.list
        cartInfos.list = dataArr;

        //make new list
        if (cartInfos.list.length > 0) {
          oList.innerHTML = cartListItem.makeList(cartInfos.list);
          reComputePrice(doms.oTotal);
          doms.oMainCheck.checked = true;
        } else {
          doms.oPurchaseBox.remove();
          oList.innerHTML = noListTip.tpl();
        }

      } else {
        toast.showToast({
          icon: 'warning',
          title: '购买失败'
        });
      }
    })
  }


  const reComputePrice = (dom) => {
    let totalPrice = 0;

    cartInfos.list.forEach((elem) => {
      if (elem.checked) {
        totalPrice += Number(elem.total_price);
      }
    });
    cartInfos.total = totalPrice;

    dom.innerHTML = cartInfos.total;
  }

  init();
}

new App(document);